<template>
  <div class="container">
    <el-card class="app-container">
      <div slot="header" class="clearfix">
        <span>用户管理</span>
      </div>
      <!-- 搜索区域 -->
      <el-form ref="searchForm" label-width="120px" :model="search" class="filter-form">
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="手机号/昵称:">
              <el-input v-model="search.search" size="small" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="状态:">
              <el-select v-model="search.status" size="small" placeholder="请选择">
                <el-option label="禁用" value="0" />
                <el-option label="启用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="12" style="display: flex; justify-content: flex-end;">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSearch">查询</el-button>
              <el-button size="medium" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div style="width: 100%;">
        <div style="margin-bottom: 15px; display: flex; justify-content: flex-start;">
          <el-button size="medium" type="primary" @click="showAddUserDialog">添加用户</el-button>
        </div>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="nickname" label="昵称" align="center" />
          <el-table-column prop="roles_id" label="权限" width="200" align="center" />
          <el-table-column prop="phone" label="手机" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column label="操作" width="175" align="center">
            <template #default="scope">
              <el-button type="text" size="small" @click="handlePassword(scope.row)">修改密码</el-button>
              <el-button style="margin-right: 10px;" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 账户信息弹框 -->
    <el-dialog :close-on-click-modal="false" class="add" title="账户信息" :visible.sync="accountDialogVisible" width="38%" @close="resetAccountForm">
      <el-form ref="accountForm" :model="accountForm" :rules="accountRules" label-width="120px">
        <el-form-item label="登录用户名" prop="username">
          <el-input v-model="accountForm.username" size="mini" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="accountForm.nickname" size="mini" />
        </el-form-item>
        <el-form-item label="用户手机号" prop="phone">
          <el-input v-model="accountForm.phone" size="mini" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="accountForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="roles_id">
          <el-checkbox-group v-model="accountForm.roles_id">
            <el-checkbox v-for="item in qxList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="accountDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAccountForm">确认</el-button>
      </span>
    </el-dialog>

    <!-- 修改密码 -->
    <el-dialog :close-on-click-modal="false" title="修改密码" :visible.sync="passwordDialogVisible" width="30%" class="xg" @close="resetPasswordDialog">
      <el-form ref="passwordForm" label-width="100px" :model="passwordForm" :rules="passwordRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="passwordForm.username" :disabled="true" size="mini" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" show-password size="mini" />
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input v-model="passwordForm.password2" type="password" show-password size="mini" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, addOrChangeUserInfo, disEnUserInfo, changeUserPassword, getQxList, getUserInfo } from '@/api/userPage'
export default {
  data() {
    return {
      qxList: [],
      search: {
        search: null,
        status: null
      },
      tableData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // popup
      accountDialogVisible: false,
      accountForm: {
        username: '',
        nickname: '',
        phone: '',
        status: '',
        roles_id: []
      },
      accountRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        roles_id: [{ required: true, message: '请选择权限', trigger: 'change' }]
      },
      // 密码
      passwordDialogVisible: false,
      passwordForm: {
        username: '',
        password: '',
        password2: '',
        id: ''
      },
      passwordRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.fetchData()

    this.getQxList()
  },
  methods: {
    async getQxList() {
      this.qxList = await getQxList()
    },
    // table状态切换
    async handleStatusChange(row) {
      const obj = {
        id: row.id
      }
      await disEnUserInfo(obj)
    },
    submitPasswordForm() {
      this.$refs.passwordForm.validate(async valid => {
        if (valid) {
          await changeUserPassword(this.passwordForm)
          this.$message.success('修改密码成功')
          this.passwordDialogVisible = false

          this.handleSearch()
        }
      })
    },
    resetPasswordDialog() {
      this.$refs.passwordForm.resetFields()
      this.passwordForm = {
        username: '',
        password: '',
        password2: '',
        id: ''
      }
    },
    resetAccountForm() {
      this.$refs.accountForm.resetFields()
      this.accountForm = {
        id: '',
        username: '',
        nickname: '',
        phone: '',
        status: '',
        roles_id: []
      }
    },
    submitAccountForm() {
      this.$refs.accountForm.validate(async valid => {
        if (valid) {
          const obj = {
            id: this.accountForm?.id || null,
            username: this.accountForm.username,
            nickname: this.accountForm.nickname,
            phone: this.accountForm.phone,
            status: this.accountForm.status,
            roles_id: this.accountForm.roles_id.join(',')
          }
          await addOrChangeUserInfo(obj)
          this.$message.success(`${this.accountForm.id ? '修改' : '添加'}用户成功`)
          this.accountDialogVisible = false
          this.handleSearch()
        }
      })
    },
    showAddUserDialog() {
      this.accountDialogVisible = true
    },
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    resetSearch() {
      this.search = {
        search: null,
        status: null
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    },
    handlePassword(row) {
      this.passwordDialogVisible = true
      this.passwordForm.username = row.username
      this.passwordForm.id = row.id
    },
    async handleEdit(row) {
      const res = await getUserInfo({
        id: row.id
      })
      this.accountDialogVisible = true
      this.accountForm = {
        id: row?.id,
        username: row?.username,
        nickname: row?.nickname,
        phone: row?.phone,
        status: row?.status,
        roles_id: res?.roles_id || []
      }
    },
    async fetchData() {
      const queryParams = {
        pageSize: this.pagination.pageSize,
        page: this.pagination.page,
        status: this.search.status,
        search: this.search.search
      }
      const res = await getUserList(queryParams)
      this.tableData = res.list
      this.pagination.total = res.total
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-radio__original {
  display: none !important;
}

::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.filter-form {
  padding: 16px;
  padding-bottom: 0;
  margin-bottom: 6px;
  .el-select {
    width: 100%;
  }
}
.tab-container {
  margin-left: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}
.filter-row > * {
  flex: 1;
  min-width: 200px;
  max-width: calc(50% - 10px);
}
.filter-actions {
  display: flex;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
.add {
  ::v-deep .el-dialog__body{
    max-height: 600px;
    overflow-y: auto;
  }
  ::v-deep .el-form-item {
    margin-bottom: 8px;
    .el-form-item__error {
      padding-top: 0px;
      transform: translateY(-2px)
    }
    .el-select {
      width: 100%;
    }
  }
}
.xg {
  ::v-deep .el-dialog__body{
    padding: 20px;
  }
}
.xxzf {
  ::v-deep .el-form-item {
    margin-bottom: 8px;
  }
  ::v-deep .el-form-item__error {
    padding-top: 0px;
    transform: translateY(-2px)
  }
  ::v-deep .el-dialog__body {
    padding: 10px 20px 15px;
  }
}
</style>
